package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.config.UserContextHolder;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IItemService itemService;

    @GetMapping("/list")
    public PageDTO GetList(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "1") Integer size
    ) {
        Page<Item> page1 = itemService.page(new Page<>(page, size));
        PageDTO<Item> itemPageDTO = new PageDTO(page1.getTotal(), page1.getRecords());
        return itemPageDTO;
    }

    @GetMapping("/{id}")
    public Item getItemByid(@PathVariable String id) {
        return itemService.getById(id);
    }

    @PostMapping
    public Object addItem(@RequestBody Item item) {
        // String s = UserContextHolder.holder.get();
        return itemService.save(item);
    }

    @PutMapping("status/{id}/{status}")
    public void Status(@PathVariable("id") String id, @PathVariable("status") String status) {
        if ("1".equals(status) || "2".equals(status)) {
            itemService.updateStatusById(id, status);
            if ("1".equals(status)) {
                // 向mq中发送消息
                rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE, MqConstants.HOTEL_INSERT_KEY, id);
            }
            if ("2".equals(status)) {
                // 向mq中发送消息
                rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE, MqConstants.HOTEL_DELETE_KEY, id);
            }
        }
    }

    @PutMapping
    public Object updateItem(@RequestBody Item item) {
        return itemService.updateById(item);
    }

    @DeleteMapping("/{id}")
    public Object deleteItemByid(@PathVariable String id) {
        return itemService.removeById(id);
    }

    @PutMapping("/stock/{itemId}/{num}")
    public void InventoryControl(@PathVariable("itemId") String itemId, @PathVariable("num") int num) {
        itemService.InventoryControl(itemId, num);
    }
    @PutMapping("/rollback/{itemId}/{num}")
    public void InventoryRollback(@PathVariable("itemId") String itemId, @PathVariable("num") int num) {
        itemService.InventoryRollback(itemId, num);
    }


}
